<template>
  <div>

    <el-container>
      <el-header height="90px" width="100%;">
        <div class="home-aside">
          <img src="../../assets/img/logo.png" alt="">
          <span>值班系统</span>
        </div>
        <div class="img-user">
          <el-dropdown @command="handleCommand" trigger="click">
            <img style="cursor:pointer" src="../../assets/img/小黄鸡.png" alt="">
            <el-dropdown-menu slot="dropdown" :split-button="true">
              <el-dropdown-item command="个人中心">个人中心</el-dropdown-item>
              <el-dropdown-item command="退出登录">退出登录</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </div>
      </el-header>
      <el-main>
        <div class="index-content">
          <el-row style="height:100%;">
            <el-col class="elcol-span1 list" style="overflow:auto; font-size:14px;" v-infinite-scroll="noticeloading"
              infinite-scroll-disabled="disabled" :span="6">

              <el-card 
                 v-for="(item) of Notice" @click.native="openNotice(item.content,item.title)" :key="item.id"
                shadow="hover">
                <div slot="header" class="clearfix">
                  <span
                    style="display:block;font-size:16px; font-weight:bold;margin: 0 0 10px 0;">标题:{{item.title}}</span>
                  <span style="">{{item.created_at}}</span>
                </div>
                <div class="index-content-info">
                  {{item.content}}
                </div>
              </el-card>
              <p style="text-align:center" v-if="noticeload">加载中...</p>
              <p style="text-align:center" v-if="noMore">没有更多了</p>

            </el-col>

            <el-col class="elcol-span2 infinite-list-wrapper" :span="18">
              <div class="chat-box " id="chat-box" ref="chatBox">
                <p style="text-align:center" v-if="loading">{{dialogMessage}}</p>
                <div v-for="item in messageAll" :key="item.id"
                  :class="item.toId != '1003' ? 'chat-box-contentleft' : 'chat-box-contentright'">
                  <div :class="item.toId != '1003' ? 'chat-box-contentleftimg' : 'chat-box-contentrightimg'">
                    <img src="../../assets/img/小黄鸡.png" alt="">
                  </div>
                  <span :class="item.atch_addr == null ? ' ' : 'itemcontent' ">
                    <span v-if="!(item.atch_addr == null)"><i class="el-icon-document"></i></span>
                    {{item.content}}
                    <el-button v-if="!(item.atch_addr == null)" @click="downLoad(item.atch_addr)" size="mini"
                      icon="el-icon-download" type="primary"></el-button>
                  </span>
                  <span>{{item.replay_time}}</span>
                </div>

              </div>

              <div v-if="progressShow" class="progress-box">
                <span>{{fileName}}</span>
                <el-progress :percentage="percentageNum" :text-inside="true" :stroke-width="20"></el-progress>
                <span><i @click="beforeRemove" class="el-icon-circle-close"></i></span>
              </div>

              <div class="input-box">
                <div class="input-box-content"  @keyup.enter="sendMessage" ref="myMessage" contentEditable="true">

                </div>

                <div class="input-box-option">
                  <el-button style="float:right; margin-right:20px; height:32px;"  @click="sendMessage" type="primary"
                    size="mini" icon="el-icon-s-promotion">发送</el-button>
                  <el-upload ref="upload" class="upload-demo" action="http://duty.myxy99.cn/api/admin/uploadfile"
                    :before-upload="beforeUpload" name="attachments" @abort='cancelUpload' :on-progress="uploadProgress"
                    :on-error="uploadError" :on-remove="handleRemove"  :on-success="uploadSuccess"
                    :headers="{ Authorization: token }"   :show-file-list="false" >
                    <el-button style="float:right" size="small" icon="el-icon-folder-opened">上传文件
                    </el-button>
                  </el-upload>


                </div>
              </div>
            </el-col>
          </el-row>
        </div>
      </el-main>

    </el-container>
    <el-dialog title="打卡时间到！" :visible.sync="centerDialogVisible" width="30%" center>
      <div style=" text-align:center; font-size:18px;">{{Date.parse(new Date()) | formatDate}}</div>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dutyCheckIn">打 卡</el-button>
      </span>
    </el-dialog>

    <el-dialog :title="noticeTitle" :visible.sync="noticeDialogVisible" width="30%" center>
      <span>{{noticeContent}}</span>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="noticeDialogVisible = false">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
  import global_ from '../../assets/js/common'
  export default {
    data() {
      return {

        user_ID:0,
        count: 10,
        noticeload: false,
        Noticecurrent_page: 1,
        NoticeTotal: 0,

        // 上传文件
        uploadAction: '',

        // 上传进度
        percentageNum: 0,
        // 显示进度条
        progressShow: false,
        // 文件名
        fileName: '',
        percentage: 0,
        centerDialogVisible: false,
        noticeDialogVisible: false,
        noticeContent: '',
        noticeTitle: '',
        // 通知内容
        Notice: [],
        // 定时器
        interval: '',
        // websocket
        websocket: null,
        ismyselfMessage: '',
        // 聊天消息
        messageAll: [

        ],
        //当前时间
        currentTime: '',
        // 历史消息当前页
        messageCurrentPage: 1,
        // 历史消息总条数
        messageTotal: 0,
        // 无限滚动条
        loading: false,
        dialogMessage: '',
        token: window.sessionStorage.getItem('token')
      }
    },
   
    created() {
      this.user_ID = window.sessionStorage.getItem("user_id")

      setInterval(() => {
        if (this.percentage < 100) this.percentage += 10;
      }, 1000);
      this.getallinfo()

      this.ismyselfMessage = true
      this.getMessageRecord()
      this.initWebSocket()
    },
    computed: {
      noMore() {
        
        return (this.NoticeTotal/10) <= this.Noticecurrent_page-1
      },
      disabled() {
        return this.noticeload || this.noMore
      }
    },
    mounted() {
      // window添加一个滚动滚动监听事件
      document.getElementById('chat-box').addEventListener('scroll', this.handleScroll)
      let vm = this;
      window.onbeforeunload = function () {
        vm.closeWebSocket()
      }
      setTimeout(() => {
        let container = this.$el.querySelector("#chat-box");
        container.scrollTop = container.scrollHeight;
      }, 300)
    },

    methods: {
      noticeloading() {
        console.log(111111);
        this.noticeload = true
        this.Noticecurrent_page++
        setTimeout(() => {
          this.getallinfo()
          this.noticeload=false
        }, 2000)
      },
      // 打卡
      dutyCheckIn() {
        // 获取当前时间
        let nowHours = new Date().getHours().toString(); //获取当前小时数(0-23)
        let nowMin = new Date().getMinutes().toString(); //获取当前分钟数(0-59)
        let nowSeconds = new Date().getSeconds().toString(); //获取当前秒数(0-59)
        function timeAdd0(str) {
          if (str.length <= 1) {
            str = '0' + str;
          }
          return str
        }
        nowHours = timeAdd0(nowHours)
        nowMin = timeAdd0(nowMin)
        nowSeconds = timeAdd0(nowSeconds)
        let nowTime = nowHours + ':' + nowMin + ':' + nowSeconds
        this.$http.post('front/puchcard', {
            puchtime: nowTime
          })
          .then(res => {
            if (res.data.code !== 200) return this.$message.error(res.data.msg)
            this.$message.success(res.data.msg)
            this.centerDialogVisible = false
          }).catch(err => {
            this.$message({
              dangerouslyUseHTMLString: true,
              showClose: true,
              message: err.response.data.data.join('<br>'),
              type: 'error'
            });
          })
      },



      handleRemove(file) {
        console.log(file);
      },
      handlePreview(file) {
        console.log(file);
      },
      beforeRemove() {
        return this.$confirm(`确定暂停 ${ this.fileName}上传?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$message({
            type: 'success',
            message: '暂停成功!'
          });
          this.$refs.upload.abort()
          setTimeout(() => {
            this.progressShow = false
          }, 1000)

        }).catch(() => {
          // 取消上传操作
          //  this.$http.get('admin/cancelfile')
          // .then(res => {
          //   if (res.data.code !== 200) return this.$message.error(res.data.msg)
          //   this.Notice = res.data.data.data
          // }).catch(err => {
          //   this.$message({
          //     dangerouslyUseHTMLString: true,
          //     showClose: true,
          //     message: err.response.data.data.join('<br>'),
          //     type: 'error'
          //   });
          // })

          this.$message({
            type: 'info',
            message: '已取消!'
          });

        });

      },
      // 上传进度
      uploadProgress(event, file) {
        this.fileName = file.name
        this.percentageNum = Math.trunc(event.percent)
        if (this.percentageNum >= 100) {
          this.percentageNum == 100
          setTimeout(() => {
            this.progressShow = false
          }, 500)
        }
      },
      // 文件上传之前
      beforeUpload() {
        this.progressShow = true
      },
      // 取消上传
      cancelUpload() {
        setTimeout(()=>{
          this.percentageNum = 0;
        },1000)
      },
      // 上传成功
      uploadSuccess(res) {
        this.$message.success(res.msg)
        this.sendMessage(res.data.path)
        setTimeout(()=>{
          this.percentageNum = 0;
        },1000)
      },
      // 上传失败
      uploadError(error) {
        this.$message.error(error.msg)
        this.percentageNum = 0;
        setTimeout(()=>{
          this.percentageNum = 0;
        },1000)
      },
      // 下载文件
      downLoad(address) {
        let tokentest = this.token.split(' ')
        window.location.href = global_.url + 'getfile/' + address + '?token=' + tokentest[1]
      },

      // 打卡框
      DialogVisibleClick() {
        this.centerDialogVisible = true
      },
      handleScroll() {
        var page = document.getElementById('chat-box');
        // console.log(page.scrollTop, page.clientHeight, page.scrollHeight)
        if (page.scrollTop <= 20 && !this.isheight) {
          this.dialogMessage = '加载更多...'
          this.isheight = true
          this.loading = true
          if ((this.messageTotal / 10) > (this.messageCurrentPage)) {

            console.log((this.messageTotal / 10), (this.messageCurrentPage));
            this.messageCurrentPage++;
            setTimeout(() => {
              this.getMessageRecord()
            }, 1000)
          } else {
            this.dialogMessage = '没有更多了!'
          }
        }
      },
      // 获取通知信息
      getallinfo() {
        this.$http.get('front/getallinfo', {
            params: {
              page: this.Noticecurrent_page
            }
          })
          .then(res => {

            if (res.data.code !== 200) return this.$message.error(res.data.msg)

            let newNoticeAll = res.data.data.data
            let oldNoticeAll = this.Notice
            this.Notice = newNoticeAll.concat(oldNoticeAll)

            this.NoticeTotal = res.data.data.total
            this.noticeload = false
            console.log();
          }).catch(err => {
            this.$message({
              dangerouslyUseHTMLString: true,
              showClose: true,
              message: err.response.data.data.join('<br>'),
              type: 'error'
            });
          })
      },
      // 文件上传
      imgPreview1(file1, fileList1) {
        let fileName = file1.name;
        let regex = /(.docx|.doc)$/;
        if (regex.test(fileName.toLowerCase())) {
          // console.log(fileList1);
          this.picUrl = URL.createObjectURL(file1.raw);
          this.promessage.wordname = fileList1;
        } else {
          //移除最后一个元素
          fileList1.pop();
          this.$message.error('请选择文件');
        }
      },
      // 发送消息
      sendMessage(path) {
        // 获取当前时间
        let that = this
      let time = that.$options.filters["formatDate"];
      let times = time(Date.parse(new Date()));

        let oneMessage
        let oneMessage1
        console.log(that.percentageNum);
        if (that.percentageNum == 100) {
          oneMessage = {
            code: 201,
            fromId: that.user_ID,
            toId: 1003,
            fromName: "甲",
            toName: "张敖",
            content: that.fileName,
            atch_addr: path,
            replay_time: times
          }
           oneMessage1 = {
            code: 201,
            fromId: that.user_ID,
            toId: 1003,
            fromName: "甲",
            toName: "张敖",
            content: that.fileName,
            atch_addr: path,
            replay_time: Date.parse(new Date())
          }
        } else {
          oneMessage = {
            code: 201,
            fromId: that.user_ID,
            toId: 1003,
            fromName: "甲",
            toName: "张敖",
            content: that.$refs.myMessage.innerText,
            atch_addr: null,
            replay_time: times
          }
          oneMessage1 = {
            code: 201,
            fromId: that.user_ID,
            toId: 1003,
            fromName: "甲",
            toName: "张敖",
            content: that.$refs.myMessage.innerText,
            atch_addr: '',
            replay_time: Date.parse(new Date())
          }
        }
        this.send(JSON.stringify(oneMessage1));
        this.messageAll.push(oneMessage)
        this.$refs.myMessage.innerText = ''
        setTimeout(() => {
          let container = this.$el.querySelector("#chat-box");
          container.scrollTop = container.scrollHeight;
        }, 50)

        console.log(this.messageAll);

      },

      // 打开通知详细信息
      openNotice(content, title) {
        this.noticeDialogVisible = true;
        this.noticeContent = content;
        this.noticeTitle = title;
      },
      // 点击下拉菜单事件
      handleCommand(command) {
        // 清空token 跳转修页面
        if (command == '个人中心') {
          this.$router.push('/personalcenter')
        } else {
           window.sessionStorage.clear()
           this.$router.push('/login')
        }
      },
      uploadopen() {

      },
      // websocket执行函数
      initWebSocket() {
        var that = this;
        if ('WebSocket' in window) {
          that.websocket = new WebSocket("ws://39.106.33.62:9502?fromId="+that.user_ID+"&toId=1003");
        } else if ('MozWebSocket' in window) {
          that.websocket = new WebSocket("ws://39.106.33.62:9502?fromId="+that.user_ID+"&toId=1003");
        } else {
          that.$message.success('浏览器不支持websocket')
          // console.log('当前浏览器 Not support websocket');

          that.interval = window.setInterval(function () { //每隔30秒钟发送一次心跳，避免websocket连接因超时而自动断开
            that.forgeWebSocket();
          }, 30000);
        }

        that.interval = window.setInterval(function () { //每隔30秒钟发送一次心跳，避免websocket连接因超时而自动断开
          if (that.websocket != null) {
            // that.websocket.send("HeartBeat");
            // console.log("发送心跳包：HeartBeat");
          }
        }, 30000);

        //连接发生错误的回调方法
        that.websocket.onerror = function (ev) {
          console.log(ev, 'error');
          console.log("WebSocket连接发生错误!");
          that.$message.error('WebSocket连接发生错误!')
        };

        //连接成功建立的回调方法
        that.websocket.onopen = function () {
          console.log("WebSocket连接成功!");
        }
        //接收到消息的回调方法
        that.websocket.onmessage = function (event) {
          console.log(event.data);
          let reutrnMessage = JSON.parse(event.data)
          if (reutrnMessage.code == 102) {
            that.centerDialogVisible = true
          } else if (reutrnMessage.code == 100) {
            let returnNotice = {
              id: 1,
              title: returnNotice.title,
              content: reutrnMessage.content,
              created_at: reutrnMessage.time
            }
            that.Notice.push(returnNotice)
          } else if (reutrnMessage.code == 201) {
            let time = that.$options.filters["formatDate"];
            let times = time(reutrnMessage.time);
            let oneMessage
            if (reutrnMessage.file == '') {
              oneMessage = {
                code: 201,
                fromId: 1003,
                toId: that.user_ID,
                fromName: "甲",
                toName: "张敖",
                content: reutrnMessage.content,
                atch_addr: null,
                replay_time: times
              }
              
            } else {
              oneMessage = {
                code: 201,
                fromId: 1003,
                toId: that.user_ID,
                fromName: "甲",
                toName: "张敖",
                content: reutrnMessage.content,
                atch_addr: reutrnMessage.file,
                replay_time: times
              }
               
            }
           
            that.messageAll.push(oneMessage)
            console.log(that.messageAll);
          }
        }
        //连接关闭的回调方法
        that.websocket.onclose = function () {
          that.$message.error('连接已断开!')
          // console.log("WebSocket连接关闭");
          that.websocket = null;
        }
      },
      //发送消息
      send(message) {
        if (this.websocket && this.websocket != null) {
          this.websocket.send(message);
          console.log("发送的消息：" + message);
        }
      },
      //关闭WebSocket连接
      closeWebSocket() {
        if (this.websocket != null) {
          this.websocket.onclose()
          console.log("已执行closeWebSocket中关闭websocket操作");
        }
        if (this.interval) {
          window.clearInterval(this.interval);
          console.log("清除定时器");
        }
      },
      // 获取历史记录的函数
      getMessageRecord() {
        this.$http.get('admin/msgrecord', {
            params: {
              fromuser_id: 0,
              page: this.messageCurrentPage
            }
          })
          .then(res => {
            if (res.data.code !== 200) return this.$message.error(res.data.msg)
            let newMessageAll = res.data.data.data
            newMessageAll.reverse()
            let oldMessageAll = this.messageAll
            this.messageAll = newMessageAll.concat(oldMessageAll)
            this.messageTotal = res.data.data.total
            this.$nextTick(() => {
              this.$refs.chatBox.scrollTop = 1000;
              setTimeout(() => {
                this.isheight = false
              }, 200)
            })
          }).catch(err => {
            console.log(err.response);
            this.$message({
              dangerouslyUseHTMLString: true,
              showClose: true,
              message: err.response.data.join('<br>'),
              type: 'error'
            });
          })
      }
    },
     filters: {
      formatDate: function (value) {
        let date = new Date(value);
        let y = date.getFullYear();
        let MM = date.getMonth() + 1;
        MM = MM < 10 ? ('0' + MM) : MM;
        let d = date.getDate();
        d = d < 10 ? ('0' + d) : d;
        let h = date.getHours();
        h = h < 10 ? ('0' + h) : h;
        let m = date.getMinutes();
        m = m < 10 ? ('0' + m) : m;
        let s = date.getSeconds();
        s = s < 10 ? ('0' + s) : s;
        return y + '-' + MM + '-' + d + ' ' + h + ':' + m + ':' + s;
      }
    },
    beforeDestroy() {
      this.closeWebSocket()
      // 清除上拉监听
      document.getElementById('chat-box').removeEventListener('scroll', this.handleScroll)

    }
  }
</script>

<style lang='less' scoped>
  .el-header {
    background: #fff;
    z-index: 100;
    box-shadow: 0 5px 7px 0px rgba(0, 0, 0, 0.1);
  }

  .home-aside {
    border-bottom: 3px solid rgba(35, 131, 240, .66);
    margin: 20px 20px 0 20px;
    padding: 0 0 10px 0;
    display: inline-block;
    width: 175px;

    span {
      font-size: 24px;
      font-weight: 400;
      color: rgba(0, 0, 0, 0.9);
      line-height: 60px;
      vertical-align: top;
      margin-left: 20px;
    }
  }

  .title {
    width: 200px;
    font-size: 14px;
    float: right;
    margin-top: 20px;
    text-align: center;
    line-height: 26px;
  }

  .img-user {
    float: right;
    margin-top: 10px;
    width: 62px;
    height: 62px;
    padding: 8px 13px;
    box-sizing: border-box;
    background: rgba(255, 255, 255, 1);
    box-shadow: 0px 0px 7px 0px rgba(0, 0, 0, 0.1);
    border-radius: 50%;
  }

  .el-main {
    background: url('../../assets/img/bg1.png') no-repeat;
    background-size: cover;
    background-position: center;
    height: 847px;
    position: relative;
  }

  // 主题内容
  .index-content {
    width: 78%;
    height: 90%;
    background: darkorange;
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
    background: rgba(255, 255, 255, 1);
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.5)
  }

  .index-content-info {
    display: inline-block;
    white-space: nowrap;
    width: 100%;
    overflow: hidden;
    text-overflow: ellipsis;
  }

  .elcol-span1 {
    box-sizing: border-box;
    border: 1px solid rgba(0, 0, 0, 0.2);
    padding: 25px;
    height: 100%;
  }

  .elcol-span2 {
    height: 100%;
  }

  .el-card {

    background: #f9fafc;
    width: 100%;
    cursor: pointer;
    margin-bottom: 20px;
  }

  .chat-box {
    margin-top: 20px;
    padding: 10px;
    height: 60%;

    overflow: auto;
  }

  .chat-box-contentleft {
    width: 100%;
    display: block;
    height: auto;
    margin: 30px 0;

    .chat-box-contentleftimg {
      display: inline-block;
      width: 55px;
      height: 55px;
      background: rgba(255, 255, 255, 1);
      box-shadow: 0px 0px 7px 0px rgba(0, 0, 0, 0.3);
      border-radius: 50%;
      box-sizing: border-box;
      padding: 5px 9px;
      margin-right: 20px;
      vertical-align: top;
    }

    >span:nth-of-type(1) {
      height: auto;
      padding: 10px 20px;
      background: rgba(255, 255, 255, 1);
      border: 2px solid rgba(0, 0, 0, 0.5);
      border-radius: 10px;
      max-width: 60%;
      line-height: 30px;
      padding: 10px 20px;
      margin-right: 20px;
      display: inline-block;
      vertical-align: middle;

    }
  }

  .chat-box-contentright {
    margin: 30px 0;
    width: 100%;
    height: auto;
    display: block;
    direction: rtl;
    min-height: 55px;

    .chat-box-contentrightimg {

      width: 55px;
      display: inline-block;
      height: 55px;
      background: rgba(255, 255, 255, 1);
      box-shadow: 0px 0px 7px 0px rgba(0, 0, 0, 0.3);
      border-radius: 50%;
      box-sizing: border-box;
      padding: 5px 9px;
      vertical-align: top;
    }

    >span:nth-of-type(1) {
      display: inline-block;
      padding: 10px 20px;
      height: auto;
      background: rgba(255, 255, 255, 1);
      border: 2px solid rgba(0, 0, 0, 0.5);
      border-radius: 10px;
      margin-right: 20px;
      line-height: 30px;
      max-width: 60%;
      vertical-align: middle;
    }

    >span:nth-of-type(2) {
      margin-right: 20px;
    }

    .chat-box-contentrightimg,
    span {
      display: inline-block;
      direction: ltr;
    }


  }

  .input-box {
    height: 30%;
    padding: 20px;
    border-top: 2px solid rgba(0, 0, 0, 0.2);

  }

  .input-box-content {
    outline: none;
    font-size: 18px;
    border: 1px solid rgba(0, 0, 0, .2);
    overflow-y: auto;
    border-radius: 5px;
    padding: 5px 10px;
    height: 65%;
  }

  .input-box-option {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;

    .upload-demo {
      display: inline-block;
      margin-right: 20px;
    }
  }

  // 进度条
  .progress-box {

    z-index: 2000;
    display: flex;
    padding-bottom: 5px;
    justify-content: center;

    .el-progress {
      width: 50%;
      margin: 0 20px;
    }

    span {
      font-weight: bold;
      font-size: 14px;
    }

    span:nth-of-type(2) {
      cursor: pointer;
      display: inline-block;
    }
  }


  .itemcontent {
    cursor: pointer;
    background: rgba(0, 0, 0, 0.02) !important;
    border-radius: 5px !important;
  }
</style>